import { Input } from 'antd'
import React, {useMemo } from 'react'
import { CommonSmallSvg } from '@/pages/workflow/components/CommonSmallTemp'
import { CommonSmallAdddButton } from '../common'
import InputWithParamsV2 from '@/pages/workflow/components/InputWithParamsV2'
import { useSourceOptions } from '@/pages/workflow/hooks/use-source-options'

const KeyValueEditor = ({ value = [], onChange, info }) => {
  const handleAdd = () => {
    onChange([...value, { key: '', value: '' }])
  }

  const handleDelete = (index: number) => {
    const newValue = [...value]
    newValue.splice(index, 1)
    onChange(newValue)
  }

  const handleChange = (index: number, field: 'key' | 'value', newValue: string) => {
    const newList = value.map((item, i) => {
      if (i === index) {
        return { ...item, [field]: newValue }
      }
      return item
    })
    onChange(newList)
  }

  const { options } = useSourceOptions(info)
  
  // 转换 options 格式为 TextareaWithParamsV2 需要的格式
  const variableOptions = useMemo(() => {
    return options.reduce((acc, group) => {
      group.options.forEach(item => {
        acc.push({
          name: item.label,
          value: item.value,
          group: group.label
        })
      })
      return acc
    }, [])
  }, [options])

  return (
    <div>
      <div className="flexRowStart columns-title--dGaYetSzjjUdXN_u9_8J ml-1">
        <div className="input-head" style={{ width: '140px' }}>
          参数名
        </div>
        <div className="input-head w-[calc((92%-140px)*0.4)] mt-1">参数值</div>
      </div>
      {value.map((item, index) => (
        <div key={index} className="flexRowStart flexRowJustBet InputCont_marTop pt-1">
          <div className="flexRowStart flexRowJustBet w-[92%]">
            <div className="w-[140px] mr-1">
              <Input
                value={item.key}
                onChange={e => handleChange(index, 'key', e.target.value)}
                placeholder="输入参数名称"
              />
            </div>
            <div className="inputCont_end" style={{ width: 'calc(100% - 140px)' }}>
              <InputWithParamsV2
                value={item.value}
                onChange={value => handleChange(index, 'value', value)}
                style={{ width: '100%' }}
                citeOptions={variableOptions}
                placeholder="'/'快速插入变量"
                triggerChar="/"
              />
            </div>
          </div>
          <div className="flex items-center">
            {index === value.length - 1 && <CommonSmallAdddButton addOption={handleAdd} />}
            {index > 0 && <CommonSmallSvg delOption={handleDelete} i={index} />} 
          </div>
        </div>
      ))}
    </div>
  )
}

export default KeyValueEditor